export class BeidouGridCode {
  // 网格级别常量定义
  static GRID_LEVELS = {
    LEVEL_1: { lon: 6, lat: 4 },
    LEVEL_2: { lon: 30/60, lat: 30/60 },
    LEVEL_3: { lon: 15/60, lat: 10/60 },
    LEVEL_4: { lon: 1/60, lat: 1/60 },
    LEVEL_5: { lon: 4/3600, lat: 4/3600 },
    LEVEL_6: { lon: 2/3600, lat: 2/3600 },
    LEVEL_7: { lon: 1/(3600*4), lat: 1/(3600*4) },
    LEVEL_8: { lon: 1/(3600*32), lat: 1/(3600*32) },
    LEVEL_9: { lon: 1/(3600*256), lat: 1/(3600*256) },
    LEVEL_10: { lon: 1/(3600*2048), lat: 1/(3600*2048) }
  };

  // 生成32位二进制编码
  static generateBinaryCode(lon, lat, height, level) {
    // 计算网格编号
    const gridLevel = this.GRID_LEVELS[`LEVEL_${level}`];
    const lonIndex = Math.floor((lon + 180) / gridLevel.lon);
    const latIndex = Math.floor((lat + 90) / gridLevel.lat);
    
    // 转换为32位二进制
    let binaryStr = '';
    
    // 添加高度信息（前8位）
    const heightBits = Math.min(Math.floor(height / 10), 255).toString(2).padStart(8, '0');
    binaryStr += heightBits;
    
    // 添加经纬度信息（后24位）
    const positionBits = (lonIndex * 1000000 + latIndex).toString(2).padStart(24, '0');
    binaryStr = binaryStr + positionBits;
    
    return binaryStr.padStart(32, '0');
  }

  // 生成北斗网格位置码
  static generate3DCode(lon, lat, height, level) {
    const binaryStr = this.generateBinaryCode(lon, lat, height, level);
    console.log(binaryStr,"binaryStr");
    // 按照公式C.14提取编码
    const a11 = parseInt(binaryStr.slice(32 - 3, 32), 2).toString(8);
    const a10 = parseInt(binaryStr.slice(32-6, 32-3), 2).toString(8);
    const a9 = parseInt(binaryStr.slice(32-9, 32-6), 2).toString(8);
    const a8 = parseInt(binaryStr.slice(32-12, 32-9), 2).toString(8);
    const a7 = parseInt(binaryStr[32 - 13], 2).toString(2);
    const a6 = parseInt(binaryStr.slice(32-17, 32-13), 2).toString(16).toUpperCase();
    const a5 = parseInt(binaryStr.slice(32-21, 32-17), 2).toString(16).toUpperCase();
    const a4 = parseInt(binaryStr[32 - 22], 2).toString(2);
    const a3 = parseInt(binaryStr.slice(32-25, 32-22), 2).toString(8);
    const a21 = parseInt(binaryStr.slice(32-31, 32-25), 2).toString(10).padStart(2, '0');
    const a0 = parseInt(binaryStr[32 - 32], 2).toString(2);

    return `N${a0}${a21}${a3}${a4}${a5}${a6}${a7}${a8}${a9}${a10}${a11}`;
  }

  // 生成2D网格位置码
  static generate2DCode(lon, lat, level) {
    const gridLevel = this.GRID_LEVELS[`LEVEL_${level}`];
    const lonIndex = Math.floor((lon + 180) / gridLevel.lon);
    const latIndex = Math.floor((lat + 90) / gridLevel.lat);
    return `L${level}-${lonIndex}-${latIndex}`;
  }
} 